﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;

namespace Test
{
    [DataContract]
    [Serializable]
    public class Inventory
    {
        #region Events
        public static event EventHandler<InventoryArgs> InventoryAddedEvent;
        public static event EventHandler<InventoryArgs> InventoryChangedEvent;
        public static event EventHandler<InventoryArgs> OutofStockEvent;
        #endregion 

        #region Properties
        [DataMember]
        public int ProductID { get; set; }
        [DataMember]
        public string ProductName{get;set;}
        [DataMember]
        public int CurrentInventory { get; set; }
        #endregion

        #region Static Properties 
        private static List<Inventory> InventoryList = new List<Inventory>();
        #endregion

        #region Static Methods
        public static Inventory GetInventory(int productid)
        {
            lock (InventoryList)
            {
                return InventoryList.FirstOrDefault(i => i.ProductID == productid);
            }
        }
        public static Inventory[] GetInventoryList()
        {
            lock (InventoryList)
            {
                return InventoryList.ToArray();
            }
        }
        #endregion

        #region Methods
        public Inventory(string creator,string name, int initnumber)
        {
            this.ProductName = name;
            this.CurrentInventory = initnumber;
            if (InventoryList.Count == 0) this.ProductID = 1;
            else this.ProductID = InventoryList.Max(i => i.ProductID)+1;
            InventoryList.Add(this);
            if (InventoryAddedEvent != null) InventoryAddedEvent
                (null, new InventoryArgs() { ChangedNumber = initnumber, Inventory = this, Operator = creator });
        }
        public bool ChangeInventory(string user, int number)
        {
            int restnumber = this.CurrentInventory + number;
            if (restnumber > 0)
            {
                this.CurrentInventory += number;
                if (InventoryChangedEvent != null) 
                    InventoryChangedEvent(null, new InventoryArgs { Inventory = this, ChangedNumber = number, Operator=user });
                return true;
            }
            else
            {
                if (OutofStockEvent != null)
                    OutofStockEvent(null, new InventoryArgs { Inventory = this, ChangedNumber = number, Operator = user });
                return false;
            }
            
        }
        #endregion
    }
}
